package android.slc.app.startup.task;

import android.slc.app.shutdown.ShutdownManager;
import android.slc.app.startup.TaskConstant;
import android.slc.base.api.slc.SlcApi;
import android.slc.base.repository.local.sp.AppConfig;
import android.slc.base.config.ConstantsBase;
import android.slc.base.utils.AppPathUtils;
import android.slc.base.utils.SlcCrashUtils;
import android.slc.box.anchors.task.Task;
import android.slc.box.core.utils.ConsoleManager;
import android.slc.module.component.image_loader.ImageLoaderConfig;
import android.slc.module.component.mock.MockManager;
import android.slc.module.project.repository.local.ProjectConfig;
import android.slc.utils.SlcFileUtils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import org.jetbrains.annotations.NotNull;

import java.io.File;

public class TaskSlc extends Task {

    public TaskSlc() {
        super(TaskConstant.TASK_SLC, false);
    }

    @Override
    protected void run(@NotNull String s) {
        if (AppConfig.isIsRelease()) {
            new ConsoleManager().initialize();
        }
        //app的启动exe文件位置
        File appFile = FileUtil.file(FileUtil.getParent(SlcFileUtils.getUserDirPath(), 1), AppConfig.getAppExeName());
        SlcCrashUtils.init(new SlcOnCrashListener(appFile));
        //初始化api
        SlcApi.init();
        //初始化MockManager
        MockManager.getInstance().init(ProjectConfig.getInstance().isOpenMock(), ProjectConfig.getInstance().getMockPeriod());
        //imagerLoader初始化
        ConstantsBase.Value.REC_CACHE_PATH = AppPathUtils.createAppCacheFile("file").getAbsolutePath();
        ImageLoaderConfig.getInstance().setSavePath(ConstantsBase.Value.REC_CACHE_PATH);
    }

    private static class SlcOnCrashListener implements SlcCrashUtils.OnCrashListener {
        private final File appFile;

        public SlcOnCrashListener(File appFile) {
            this.appFile = appFile;
        }

        @Override
        public void onCrash(String crashInfo, Throwable e, SlcCrashUtils.OnNotifyUncaughtExceptionListener onNotifyUncaughtExceptionListener) {
            onNotifyUncaughtExceptionListener.onNotifyUncaughtException(e);
            if (e instanceof OutOfMemoryError && ProjectConfig.getInstance().isAutoRestart()) {
                ShutdownManager.shutdown();
                try {
                    if (appFile.exists()) {
                        RuntimeUtil.execForStr(StrUtil.format("\"{}\"", appFile.getAbsolutePath()));
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                } finally {
                    System.exit(0);
                }
            }
        }
    }
}
